package com.wyg.demo.exception;

import com.wyg.demo.common.CommonResult;
import com.wyg.demo.common.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;

/**
 * @author ygWen
 * @Description: 全局异常处理类
 * @date 2021/12/30
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 业务异常
     */
    @ExceptionHandler(ServiceException.class)
    public CommonResult<Void> handleServiceException(ServiceException e, HttpServletRequest request)
    {
        log.error(e.getMessage(), e);
        Integer code = e.getCode();
        if (null != code) {
            return CommonResult.failed(code, e.getMessage());
        } else {
            return CommonResult.failed(e.getMessage());
        }
    }
    
    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public CommonResult<Void> handleRuntimeException(RuntimeException e, HttpServletRequest request)
    {
        String requestUri = request.getRequestURI();
        log.error("请求地址'{}',发生未知异常.", requestUri, e);
        return CommonResult.failed("发生未知异常");
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public CommonResult<Void> handleException(Exception e, HttpServletRequest request)
    {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',发生系统异常.", requestURI, e);
        return CommonResult.failed("发生系统异常");
    }

    /**
     * 数据库异常
     */
    @ExceptionHandler(SQLException.class)
    public CommonResult<Void> handleSqlException(SQLException e){
        if (e instanceof SQLIntegrityConstraintViolationException){
            return CommonResult.failed("该数据有关联数据，操作失败！");
        }
        return CommonResult.failed("数据库异常，操作失败");
    }
}
